<?php
/**
 * Created by PhpStorm.
 * User: luoqinghui
 * Date: 2020/7/24
 * Time: 上午17:40
 */

namespace App\Http\Controllers\Api\Common;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;


/**
 * 图片上传
 * Class UploadImageController
 * @package App\Http\Controllers\Api\Home
 */
class UploadImageController extends Controller
{
    /**
     * base64图片上传（多图片用|分割）
     */
    public function base64Upload(Request $request)
    {
        $type = $request->input('type', 0);
        //安卓 IOS 需要转码
        $base64_img = $request->input('file');
        if (empty($base64_img)) return response()->error("UPLOAD_LACK");
        if ($type == 1) {
            $base64_img = rawurldecode($base64_img);
        }
        $base64_img = explode('|', $base64_img);     //转数组
        $datePast = date('Y-m-d',time());
        $root = public_path();
        $filePath = '/uploads/graphic/' . $datePast;
        //文件夹目录
        $up_dir = $root . $filePath;
        is_dir($up_dir) || mkdir($up_dir, 0777, true);
        $imageAll = [];
        foreach ($base64_img as $key => $base64Item) {
            if (strpos($base64Item, ';base64,') == false) $base64Item = 'data:image/png;base64,' . $base64Item;
            preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64Item, $result);
            if ($result) {
                /**
                 * array:3 [
                 * 0 => "data:image/jpeg;base64,"
                 * 1 => "data:image/jpeg;base64,"
                 * 2 => "jpeg"
                 * ]
                 */
                $type = $result[2];
                if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
                    $newImage = $up_dir . '/' . date('YmdHis') . rand(1000, 9999);    //文件名
                    $new_file = $newImage . '.' . $type;                                    //拼接后缀
                    if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64Item)))) {
                        //拼接返回名字
                        $imageName = explode('/', $new_file);
                        $imageStr = $filePath . '/' . $imageName[count($imageName) - 1];
                        array_push($imageAll, $imageStr);
                    } else {
                        return response()->error("UPLOAD_FAIL");
                    }
                } else {
                    return response()->error("UPLOAD_TYPE_ERROR");
                }
            } else {
                return response()->error("UPLOAD_MSG_FAIL");
            }
        }
        $imageAll = implode(',', $imageAll);
        return response()->success($imageAll);
    }

}
























